package com.my.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.reggie.common.R;
import com.my.reggie.dto.SetmealDishDto;
import com.my.reggie.dto.SetmealDto;
import com.my.reggie.pojo.Category;
import com.my.reggie.pojo.Dish;
import com.my.reggie.pojo.Setmeal;
import com.my.reggie.pojo.SetmealDish;
import com.my.reggie.service.CategoryService;
import com.my.reggie.service.DishService;
import com.my.reggie.service.SetmealDishService;
import com.my.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page,int pageSize,String name){
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null,Setmeal::getName,name);
        setmealService.page(pageInfo,lqw);
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<SetmealDto> lists = new ArrayList<>();
        for (Setmeal record : pageInfo.getRecords()) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record,setmealDto);
            //获取套餐id
            Long categoryId = record.getCategoryId();
            //根据id获取套餐实体
            Category category = categoryService.getById(categoryId);
            //获取套餐名称
            String Name = category.getName();
            //设置套餐名称
            setmealDto.setCategoryName(Name);
            lists.add(setmealDto);
        }
        dtoPage.setRecords(lists);
        return R.success(dtoPage);
    }

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        //删除套餐缓存
        /* String key = "setmeal_" + setmealDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        log.info(setmealDto.toString()); */
        setmealService.save(setmealDto);
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        for(SetmealDish setmealDish : dishes){
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(dishes);
        return R.success("添加成功！");
    }

    /**
     * 删除操作
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(Long[] ids){
        for(Long id : ids){
            //删除套餐缓存
            /* LambdaQueryWrapper<Setmeal> SLqw = new LambdaQueryWrapper<>();
            SLqw.eq(Setmeal::getId,id);
            Setmeal setmeal = setmealService.getOne(SLqw);
            String setmealKey = "setmeal_" + setmeal.getCategoryId() + "_1";
            redisTemplate.delete(setmealKey); */
            LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SetmealDish::getSetmealId,id);
            //删除套餐包含的菜品
            setmealDishService.remove(lqw);
            //删除套餐
            setmealService.removeById(id);
        }
        return R.success("删除成功！");
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        //拷贝属性值
        BeanUtils.copyProperties(setmeal,setmealDto);
        //查询套餐所含的菜品
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,id);
        lqw.orderByDesc(SetmealDish::getPrice);
        List<SetmealDish> dishes = setmealDishService.list(lqw);
        //设置setmealDishes属性值
        setmealDto.setSetmealDishes(dishes);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @return
     */
    @PutMapping
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        //删除缓存
        // String key = "setmeal_" + setmealDto.getCategoryId() + "_1";
        // redisTemplate.delete(key);
        //修改套餐
        setmealService.updateById(setmealDto);
        //获取套餐id
        Long setmealId = setmealDto.getId();
        //删除原来的菜品
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmealId);
        setmealDishService.remove(lqw);
        //修改套餐菜品
        for (SetmealDish setmealDish : setmealDto.getSetmealDishes()) {
            setmealDish.setSetmealId(setmealId);
            setmealDishService.save(setmealDish);
        }
        return R.success("修改成功！");
    }

    /**
     * 修改状态信息(含批量操作)
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    //采用注解删除缓存
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> status(Long[] ids, @PathVariable int status){
        log.info("ids={},status={}",ids,status);
        for(Long id : ids) {
            // LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
            // lqw.eq(Setmeal::getId,id);
            // Setmeal setmeal_temp = setmealService.getOne(lqw);
            // String key = "setmeal_" + setmeal_temp.getCategoryId() +"_1";
            //删除缓存
            // redisTemplate.delete(key);
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("修改成功！");
    }

    /**
     * 获取套餐菜品
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("/list")
    //采用注解方式缓存套餐信息
    @Cacheable(value = "setmealCache",key = "#categoryId + '_' + #status")
    public R<List<Setmeal>> list(Long categoryId,int status){
        List<Setmeal> list = null;
        /* //构造key
        String key = "setmeal_" + categoryId + "_" + status;
        list = (List<Setmeal>) redisTemplate.opsForValue().get(key);
        //缓存数据不为空，直接返回
        if(list != null) {
            return R.success(list);
        } */
        //缓存数据为空
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(categoryId != null,Setmeal::getCategoryId,categoryId);
        lqw.eq(Setmeal::getStatus,status);
        list = setmealService.list(lqw);
        //将数据缓存到Redis
        // redisTemplate.opsForValue().set(key,list,60, TimeUnit.MINUTES);
        return R.success(list);
    }

    /**
     * 获取套餐内菜品信息(前端)
     * @param setmealId
     * @return List<SetmealDto>要包含image信息
     */
    @GetMapping("/dish/{setmealId}")
    public R<List<SetmealDishDto>> dishes(@PathVariable Long setmealId){
        //根据套餐id得到套餐内菜品列表
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> list = setmealDishService.list(lqw);
        List<SetmealDishDto> SDDList = new ArrayList<>();
        for(SetmealDish dish : list) {
            //根据菜品id得到菜品信息
            LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
            dishLqw.eq(Dish::getId,dish.getDishId());
            Dish dish1 = dishService.getOne(dishLqw);
            //获取图片信息
            String image = dish1.getImage();
            SetmealDishDto setmealDishDto = new SetmealDishDto();
            //拷贝属性信息
            BeanUtils.copyProperties(dish,setmealDishDto);
            //设置图片信息
            setmealDishDto.setImage(image);
            //添加到List
            SDDList.add(setmealDishDto);
        }
        return R.success(SDDList);
    }
}
